#include "databasetool.h"
#include <QSqlRecord>

namespace Yzty {

    std::mutex DataBaseTool::qmutex;

    DataBaseTool* DataBaseTool::_instance=nullptr;

    DataBaseTool* DataBaseTool::GetInsatnce(QObject *parent){
        if(DataBaseTool::_instance==nullptr)
            DataBaseTool::_instance=new DataBaseTool(parent);
        return DataBaseTool::_instance;
    }

    DataBaseTool::DataBaseTool(QObject *parent) : QObject(parent),query(nullptr)
    {
        this->sql=QSqlDatabase::addDatabase("QSQLITE");
    }

    DataBaseTool::~DataBaseTool()
    {
        this->sql.close();
    }

    bool DataBaseTool::SetDataBaseName(const QString &name)
    {
        bool flag=this->sql.isOpen();
        if(!flag||this->sql.databaseName()!=name){
            if(flag&&this->sql.databaseName()!=name){
                this->sql.close();
                this->sql.removeDatabase(this->sql.databaseName());
            }
            this->sql.setDatabaseName(name);
            if(this->sql.isOpen())
                return true;
        }
        return this->sql.open();
    }

    bool DataBaseTool::Execute(const QString &q)
    {
        delete query;
        query=new QSqlQuery(sql);
        return query->exec(q);
    }

    QVector<QStringList> DataBaseTool::GetResult(){
        QVector<QStringList> result;
        while(this->query->next()){
            QSqlRecord record=this->query->record();
            QStringList temp;
            for(int i=0;i<record.count();i++)
                temp.push_back(record.value(i).toString());
            result.push_back(temp);
        }
        return result;
    }

    bool DataBaseTool::IsContain(const QString &name){
        return this->sql.contains(name);
    }

    bool DataBaseTool::Transaction(){
        return this->sql.transaction();
    }

    bool DataBaseTool::RollBack(){
        return  this->sql.rollback();
    }

    bool DataBaseTool::Commit(){
        return this->sql.commit();
    }

};



